package com.example.user.service;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Author:汪彬彬
 * date:2024/11/14 17:14
 */

/**
 * 消息发布者
 */
@Service
public class MqttPublisher {

    @Autowired
    private MqttClient mqttClient;

    /**
     * 发送消息
     * @param topic
     * @param message
     * @throws MqttException
     */
    public void publish(String topic, String message) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        mqttMessage.setQos(2); // 设置QoS等级
        mqttClient.publish(topic, mqttMessage);
    }

}
